/*
 * @Author: wupeiwen <javapeiwen2010@gmail.com>
 * @Date: 2022-04-11 11:29:18
 * @LastEditors: wupeiwen <javapeiwen2010@gmail.com>
 * @LastEditTime: 2023-06-13 14:56:48
 * @FilePath: /tea-garden-web/src/util/storeModules/farming-records.js
 * @Description: 农事计划
 */
import { get } from '@/util/http.js'
export default {
  state: {
    // 查询条件
    query: '',
    // 农事计划年度统计
    annualSummary: [],
    // 选中年份
    selectedYear: '',
    // 农事计划列表
    farmingRecordList: [],
    // 加载中
    loading: {
      annualSummary: false,
      farmingRecordList: false
    }
  },
  getters: {},
  mutations: {
    // 设置查询条件
    setQuery (state, payload) {
      state.query = payload
    },
    // 设置选中年份
    setYear (state, payload) {
      state.selectedYear = payload
    },
    // 设置通用状态
    setCommonState (state, payload) {
      const { key, value } = payload
      state[key] = value
    },
    // 设置加载状态
    setLoadingState (state, payload) {
      const { key, value } = payload
      state.loading[key] = value
    }
  },
  actions: {
    // 获取农事计划年度统计
    async getAnnualSummary ({ state, commit, dispatch }) {
      try {
        commit('setLoadingState', { key: 'annualSummary', value: true })
        commit('setCommonState', { key: 'annualSummary', value: [] })
        const { data } = await get({ url: '/farming/count' })
        // 插入测试数据
        // data.push({ year_date: '2021', cnt: 1 })
        // 设置选中年份

        // for (const key in data) {
        //   console.log(key)
        //   data[0].year_date = key
        // }

        const data1 = Object.keys(data).map((key) => {
          return {
            year_date: key,
            cnt: data[key]
          }
        }).reverse() // 如果你需要按年份降序排列，添加 .reverse()

        if (data1.length > 0) {
          if (state.selectedYear === data1[0].year_date) {
            dispatch('getFarmingRecordList')
          } else {
            commit('setCommonState', { key: 'selectedYear', value: data1[0].year_date })
          }
          commit('setCommonState', { key: 'annualSummary', value: data1 })
        }
      } catch (error) {
        console.log(error)
      }
      commit('setLoadingState', { key: 'annualSummary', value: false })
    },
    // 获取农事记录列表（年月）
    async getFarmingRecordList ({ commit, state }) {
      commit('setLoadingState', { key: 'farmingRecordList', value: true })
      commit('setCommonState', { key: 'farmingRecordList', value: [] })
      try {
        const { data } = await get({ url: `/farming/recordList?time1=${state.selectedYear + '-01-01'}&time2=${state.selectedYear + '-12-31'}`, params: { record_date: state.selectedYear } })
        // data的格式[{plan_time: '2022-03-17'}], plan_time字段按照月份，对data中的元素聚合
        const monthObj = {}
        data.forEach(item => {
          const date = item.planTime.split('-')
          const month = date[0] + '年' + date[1] + '月'
          if (monthObj[month]) {
            monthObj[month].push(item)
          } else {
            monthObj[month] = [item]
          }
        })
        // 将monthObj的元素中的data按照日期进行聚合
        Object.keys(monthObj).forEach(key => {
          const dayObj = {}
          monthObj[key].forEach(item => {
            const date = item.planTime.split('-')
            const day = date[1] + '月' + date[2] + '日'
            if (dayObj[day]) {
              dayObj[day].push(item)
            } else {
              dayObj[day] = [item]
            }
          })
          monthObj[key] = Object.keys(dayObj).map(key => {
            return {
              day: key,
              data: dayObj[key]
            }
          })
        })
        // 将monthObj转成数组
        const monthArr = Object.keys(monthObj).map(key => {
          return {
            month: key,
            data: monthObj[key]
          }
        })
        commit('setCommonState', { key: 'farmingRecordList', value: monthArr.reverse() })
      } catch (error) {
        console.log(error)
      }
      commit('setLoadingState', { key: 'farmingRecordList', value: false })
    }
  }
}
